package com.trailer.base.net

import com.tencent.mmkv.MMKV
import com.trailer.base.base.BApp
import com.trailer.base.utils.Base64Util
import com.trailer.base.utils.MD5Utils
import com.trailer.base.utils.ParamUtils
import okhttp3.*
import java.security.KeyFactory
import java.security.NoSuchAlgorithmException
import java.security.PublicKey
import java.security.spec.X509EncodedKeySpec
import javax.crypto.Cipher


/**
 *
 *on 2020/11/9
 */
class CommonInterceptor() : Interceptor {


    override fun intercept(chain: Interceptor.Chain): Response {

        var request = chain.request()
        //获取请求体
        var body = request.body()
        val formMap: MutableMap<String, String> = HashMap()

        if (body is FormBody) {
            val formBody = body
            // 从 formBody 中拿到请求参数，放入 formMap 中
            for (i in 0 until formBody.size()) {
                formMap[formBody.name(i)] = formBody.value(i)
            }
        }
        //添加公共参数
        var requestNumber = ParamUtils.getRandomString(10)
        var version = BApp.instance()?.config()?.getVersionName()
        var source = "android"
        formMap["requestNumber"] = requestNumber
        formMap["version"] = "" + version
        formMap["source"] = source

        var token=MMKV.defaultMMKV().decodeString("token", "")
        if(null!=token&&!token.equals("")){
            formMap["token"] = token
        }

        val list: List<Map.Entry<String, String>> = MD5Utils.sortMap(formMap)

        val signBuilder = StringBuilder()
        for (item in list) {
            signBuilder.append(item.value)
        }
        var sign = MD5Utils.getMD5(signBuilder.toString() + "zxcvbnm")


        // 添加新的参数
        val authorizedUrlBuilder: HttpUrl.Builder = request.url()
            .newBuilder()
            .scheme(request.url().scheme())
            .host(request.url().host())
            .addQueryParameter("sign", sign)
            .addQueryParameter("requestNumber", requestNumber)
            .addQueryParameter("version", version)
            .addQueryParameter("source", source)
            .addQueryParameter("token", token)

        // 新的请求
        val newRequest: Request = request.newBuilder()
            .method(request.method(), request.body())
            .url(authorizedUrlBuilder.build())
            .build()
        return chain.proceed(newRequest)



    }


//        var request = chain.request()
//        //获取请求体
//        var body: RequestBody? = request.body()
//        if (body is FormBody) {
//            val formBody = body
//            val formMap: MutableMap<String, String> = HashMap()
//            // 从 formBody 中拿到请求参数，放入 formMap 中
//            for (i in 0 until formBody.size()) {
//                formMap[formBody.name(i)] = formBody.value(i)
//            }
//            //添加公共参数
//            var requestNumber = ParamUtils.getRandomString(10)
//            var version = BApp.instance()?.config()?.getVersionName()
//            var source = "android"
//            formMap["requestNumber"] = requestNumber
//            formMap["version"] = "" + version
//            formMap["source"] = source
//
//            val list: List<Map.Entry<String, String>> = MD5Utils.sortMap(formMap)
//
//            val signBuilder = StringBuilder()
//            for (item in list) {
//                signBuilder.append(item.value)
//            }
//            var sign = MD5Utils.getMD5(signBuilder.toString() + "zxcvbnm")
//
//            // 重新修改 body 的内容
//            body = FormBody.Builder().add("sign", sign)
//                .add("requestNumber",requestNumber)
//                .add("version",version)
//                .add("source",source)
//                .build()
//        }
//
//        // 若请求体不为Null，重新构建post请求，并传入修改后的参数体
//        if (body != null) {
//            request= request.newBuilder().post(body).build()
//        }
//        return chain.proceed(request)







        /**
         * 得到公钥
         *
         * @param bysKey
         * @return
         */
        @Throws(NoSuchAlgorithmException::class, java.lang.Exception::class)
        private fun getPublicKeyFromX509(bysKey: String): PublicKey? {
            val decodedKey: ByteArray = Base64Util.decode(bysKey)
            val x509 = X509EncodedKeySpec(decodedKey)
            val keyFactory: KeyFactory = KeyFactory.getInstance("RSA")
            return keyFactory.generatePublic(x509)
        }

        /**
         * 使用公钥加密
         *
         * @param content 密文
         * @param pub_key 公钥
         * @return
         */
        fun encryptByPublic(content: String, pub_key: String?): String? {
            return try {
                val pubkey = getPublicKeyFromX509(pub_key!!)
                val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
                cipher.init(Cipher.ENCRYPT_MODE, pubkey)
                val plaintext = content.toByteArray(charset("UTF-8"))
                val output = cipher.doFinal(plaintext)
                (Base64Util.encode(output)).toString()
            } catch (e: java.lang.Exception) {
                null
            }
        }


    }
